package com.hmall.item.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.PageDTO;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @GetMapping("/list")
    public PageDTO<Item> list(@RequestParam(defaultValue = "1") Integer page ,
                        @RequestParam(defaultValue = "5") Integer size){
        return itemService.Page(page,size);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PutMapping("/status/{id}/{status}")
    public void less(@PathVariable Long id,
                     @PathVariable Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
//        查询数据
        Item item1 = itemService.getById(id);
//        发送消息到RabbitMQ
        String json = JSON.toJSONString(item1);
//        发型消息，指定交换机，路由，数据
        rabbitTemplate.convertAndSend("item.direct","item.insert",json);
    }

    @PostMapping
    public void Insert(@RequestBody Item item){
        item.setCreateTime(new Date());
        itemService.save(item);

    }
    @PutMapping
    public void Update(@RequestBody Item item){
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        Item item = itemService.getById(id);
        return item;
    }
    @DeleteMapping("/{id}")
    public void  Delete(@PathVariable Long id){
        itemService.removeById(id);
    }

    @PutMapping("/stock/{itemId}/{num}")
    public void reduceStock(@PathVariable Long itemId,
                     @PathVariable Integer num){
        Item item = itemService.getById(itemId);
        item.setStock(item.getStock() - num);
        itemService.updateById(item);
    }
}
